package com.otdemo.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.otdemo.dao.RestContentDao;
import com.otdemo.dao.RestScoreDao;
import com.otdemo.dao.RestUserDao;
import com.otdemo.entity.RestContent;
import com.otdemo.entity.RestScore;
import com.otdemo.entity.RestUser;
import com.otdemo.resp.ResultResponse;
import com.otdemo.type.RoleEnum;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@WebServlet("/score/edit")
public class ScoreEditController extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		List<RestContent> contentList = new RestContentDao().list();
		List<RestUser> userList = new RestUserDao().list();
		userList = userList.stream().filter(p -> RoleEnum.user.getCode().equals(p.getRole())).collect(Collectors.toList());
		req.setAttribute("contentList", contentList);
		req.setAttribute("userList", userList);
		req.getRequestDispatcher("/ScoreAdd.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setCharacterEncoding("UTF-8");
		BufferedReader reader = req.getReader();
		String s = reader.readLine();
		RestScore rest = new ObjectMapper().readValue(s, RestScore.class);
		new RestScoreDao().update(rest);
		ResultResponse resultResponse = new ResultResponse();
		resp.getWriter().write(new ObjectMapper().writeValueAsString(resultResponse.success()));
	}
}
